package com.shungen.apicloud.utils;

import org.springframework.beans.factory.annotation.Value;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;


/**
 * 邮箱工具类
 */
public class EmailUtil {

    @Value("${email.username}")
    private String username;

    @Value("${email.password}")
    private String password;
    private final Properties properties;

    public EmailUtil() {
        this.properties = new Properties();
        this.properties.put("mail.smtp.auth", "true");
        this.properties.put("mail.smtp.starttls.enable", "true");
        this.properties.put("mail.smtp.host", "smtp.qq.com");
        this.properties.put("mail.smtp.port", "587");
        this.properties.put("mail.smtp.ssl.trust", "smtp.qq.com");
    }

    public void sendEmail(String toAddress, String subject, String messageBody) throws MessagingException {
        Session session = Session.getInstance(this.properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
        message.setSubject(subject);
        message.setText(messageBody);

        Transport.send(message);
    }

    public static void main(String[] args) {

    }
}
